package com.psdi.window;

import com.psdi.Main;
import com.psdi.element.ElementObject;
import com.psdi.element.Tag;
import com.psdi.manager.ElementManager;

import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.Map;

/**
 * 游戏主面板类
 * 负责显示游戏中的各种元素
 * 多线程
 */
public class GameMainPanel extends JPanel implements Runnable {
    private ElementManager elementManager;

    public GameMainPanel() {
        initComponents();
    }

    private void initComponents() {
        elementManager = ElementManager.getINSTANCE();
    }

    /**
     * 重写paint方法，用于绘制游戏元素
     *
     * @param g 图形上下文
     */
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g); // 更高效的绘制流程
        Map<Tag, List<ElementObject>> gameElements = elementManager.getGameElements();
        for (Tag tag : Tag.values()) {
            List<ElementObject> elementObjects = gameElements.get(tag);
            for (int i = 0; i < elementObjects.size(); i++) {
                elementObjects.get(i).show(g); // 绘制每个元素
            }
        }
    }

    @Override
    public void run() {
        while (Main.READY) {
            repaint();
            try {
                //noinspection BusyWait
                Thread.sleep(Main.MILLI_DELTA_TIME);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
